<?php
/**
 * Description: 上传控制器
 * User: Administrator
 * Date: 2017-06-01
 * Time: 18:14
 */

namespace app\backend\controller;

use think\Controller;

class UploadController extends Controller
{
    private $_memberId  = null;
    public function __construct()
    {
        parent::__construct();
        $this->_memberId = $this->isLogin();
    }

    /**
     * 上传excel
     * @return json
     */
    public function uploadExcel()
    {
        $title = $_REQUEST['title'];
        $callback = $_REQUEST['callback'];
        $type = $_REQUEST['type'];
        if (!$title) {
            $this->apiReturn(400, [], '参数缺失');
        }
        if ($_FILES[$title]['size'] <=0) {
            $this->apiReturn(400, [], '文件信息有误');
        }
        if ($type == 2) {//物业水电费用
            $savePath = EXCEL_IMPORT_DIR . 'property_manager/access/' . $this->_memberId;
        } elseif ($type == 1) {//用户信息导入
            $savePath = EXCEL_IMPORT_DIR . 'member/access/' . $this->_memberId;
        } elseif ($type == 3) {//房源信息导入
            $savePath = EXCEL_IMPORT_DIR . 'house/access/' . $this->_memberId;
        } elseif ($type == 4) {//合同模板导入
            $savePath = EXCEL_IMPORT_DIR . 'lease/access/' . $this->_memberId;
        } else {
            echo '文件类型有误';
            exit;
        }

        include '/var/www/html/zft/application/backend/Uploader.php';
        $config  = array(
            'simpleFolder'  => true,
            "savePath"      => $savePath,
            "maxSize"       => 500, //单位KB
            "allowFiles"    => array(".xls", ".xlsx", ".csv"),
        );

        $upload = new \Uploader($_REQUEST['title'], $config, 1);
        $res = $upload->uploadExcel();
        if ($res['code'] != 200) {
            $json = "{\"status\":\"fail\", \"key\":\"".$res['msg']."\"}";
            echo '<script>window.parent.' . $callback . '('.$json.');</script>';
            die;
        }
        $info = $upload->getFileInfo();
        if ($info['state']=='SUCCESS') {
            $json = '{"status":"ok", "key":"'.str_replace(EXCEL_REMOVE_DIR, MAIN_DOMAIN, $info['url']).'", "filename":"'.$_FILES[$title]['name'].'"}';
        } else {
            $json = '{"status":"fail", "key":"上传失败"}';
        }
        echo '<script>window.parent.' . $callback . '('.$json.');</script>';
    }
}